package com.hxht.cmp.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author alice on 2017/8/22 0022.
 * @version 1.0
 * @since 1.0
 */
public class MySessionDAO extends MemorySessionDAO {
    private static Map<String,Session> sessionMap = new LinkedHashMap<>();


    @Override
    public void update(Session session) {
        if(session instanceof ValidatingSession && !((ValidatingSession)session).isValid()) {
            return; //如果会话过期/停止 没必要再更新了
        }
        sessionMap.put(session.getId().toString(),session);
    }

    @Override
    public void delete(Session session) {
        sessionMap.remove(session.getId().toString());
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        if (!ObjectUtils.isEmpty(session.getId())) {
            sessionMap.put(session.getId().toString(),session);
        }
        return sessionId;
    }

    @Override
    public Session doReadSession(Serializable serializable) {
        return sessionMap.get(serializable.toString());
    }
}
